<template>
  <div ref="chartDiv" :style="currStyle"></div>
</template>

<script setup>
import {ref, watch, onMounted, nextTick, markRaw} from 'vue';
import * as echarts from "echarts";
import visual from "@/visual/js/visual";
import * as chart from "@/visual/js/echarts";
import JSON5 from 'json5';
import { parseColors } from "@/utils/color";

const props = defineProps({
  node: Object,
  compStyle: Object,
  compData: Object
});
const currNode = ref(props.node);
const chartDiv = ref();
const currChart = ref(null);
const currStyle = ref();

const init = async() => {
  if (currNode.value.compData.dataSourceType === '') {
    currNode.value.compData.dataSourceType = '静态数据';
  }
  const compStyle = props.compStyle || {};
  let style = '';
  style += visual.parseTpl('width: {value};', compStyle['width']);
  style += visual.parseTpl('height: {value};', compStyle['height']);
  currStyle.value = style;

  let defaultOption = {};
  try {
    defaultOption = JSON5.parse(compStyle['jsonOption'] || '{}');
  } catch (e) {
    console.log("jsonOption解释出错", e)
  }
  const dataList = (await visual.loadData(props.compData, {}, {}, currNode.value)).data || [];
  currNode.value.compData.dataList = JSON.stringify(dataList);

  const seriesData = [];
  dataList.forEach(data => {
    seriesData.push({
      name: data['标签'] || data['标题'],
      value: data['系列'] || data['数值'],
    });
  });

  const option = {
    animation: compStyle['animation'] || false,
    color: parseColors(compStyle['colorScheme']),
    title: chart.parseTitle(compStyle),
    tooltip: chart.parseTooltip(compStyle),
    legend: chart.parseLegend(compStyle),
    series: [
      {
        ...parsePie(compStyle),
        data: seriesData
      }
    ],
    toolbox: chart.parseToolbox(compStyle)
  };

  await nextTick(() => {
    try {
      if (currChart.value) {
        echarts.dispose(chartDiv.value);
      }
      currChart.value = markRaw(echarts.init(chartDiv.value));
      currChart.value.setOption(Object.assign({}, option, defaultOption));
    } catch (e) {
      console.log(e);
    }
  });
  await nextTick(() => currChart.value.resize());
};

const parsePie = (compStyle) => {
  const result = { type: 'pie' };

  if (compStyle['series.padAngle']) {
    result['padAngle'] = compStyle['series.padAngle'];
  }

  if (compStyle['series.radius']) {
    result['radius'] = compStyle['series.radius'].split(',');
  }

  if (compStyle['series.borderRadius']) {
    result['itemStyle'] = {
      borderRadius: compStyle['series.borderRadius'].split(',')
    };
  }

  if (compStyle['series.rose']) {
    result['roseType'] = compStyle['series.roseType'];
  }

  if (compStyle['series.formatter']) {
    result['label'] = {
      formatter: compStyle['series.formatter'],
      color: 'inherit'
    }
  }

  return result;
};

watch(() => props.compStyle, () => {
  init();
}, { deep: true });

watch(() => props.compData?.refresh, () => {
  init();
});

onMounted(() => {
  init();
});
</script>